<template>
    <div class="" v-if="state !== 'hidden'">

        <el-form ref="form" :model="form" :label-width="'write' == state ? '115px':'auto'"
                 :class="'write' == state ? 'write-form':'read-form'"
                 :label-position="'write' == state ? 'top':'left'">

            <div class="card-wrap flex-column justify-end card-padding table_wrap">
                <div class="card-title-wrap">
                    <span>过户车辆</span>
                    <span>已选择过户车辆数量/辆：{{ form.carList && form.carList.length }}</span>
                </div>

                <el-table border
                          :data="form.carList"
                          style="width: 100%">
                    <el-table-column
                        prop="vinNo"
                        label="车架号"
                        align="center"
                        show-overflow-tooltip
                        min-width="180">
                        <template v-slot="{row}">
                            {{row.vinNo|filterNull}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="brandName"
                        align="center"
                        show-overflow-tooltip
                        label="品牌/车系/车型"
                        min-width="180">
                        <template v-slot="{row}">
                            {{row.brandName|filterNull}}/{{row.seriesName|filterNull}}/{{row.modelName|filterNull}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="sourceCarNo"
                        align="center"
                        show-overflow-tooltip
                        min-width="130"
                        label="车牌号">
                        <template v-slot="{row}">
                            {{row.sourceCarNo|filterNull}}
                        </template>
                    </el-table-column>
                    <el-table-column
                        prop="businessType"
                        align="center"
                        show-overflow-tooltip
                        min-width="100"
                        label="车辆状态">
                        <template v-slot="{row}">
                            {{ selectDictLabel(dict.type.car_business_type, row.businessType) }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        align="center"
                        show-overflow-tooltip
                        min-width="130"
                        label="上牌城市">
                        <template v-slot="{row}">
                            {{form.transferBeforeName|filterNull}}
<!--                            {{row.propertyRightName|filterNull}}-->
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="freightFee" align="center"
                        min-width="130">
                        <template slot="header" slot-scope="scope">
                            <span>运费<span class="state_red" v-if="'write' == state">*</span></span>
                        </template>

                        <template v-slot="{row}">

                            <el-form-item label-width="0" prop="freightFee"
                                          :rules="'write' == state ? [{
                                                             required: true,
                                                             message: '请输入运费',
                                                             trigger: 'blur',
                                                             validator: (rule, value, callback) => validData(rule, row.freightFee, callback)
                                                           }]:{}">
                                <el-input v-if="'write' == state" v-thousand
                                          @change="inputChange"
                                          @input="value=>{if(isNaN(row.freightFee)) { row.freightFee = '' };
                                            if(row.freightFee.indexOf('.')>0){row.freightFee=row.freightFee.slice(0,row.freightFee.indexOf('.')+3)}
                                            row.freightFee = row.freightFee.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                          v-model="row.freightFee" clearable
                                          placeholder="请输入运费"></el-input>
                                <span v-thousand v-else>{{ row.freightFee|filterNull }}</span>
                            </el-form-item>
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="transferFee" align="center"
                        min-width="150">
                        <template slot="header" slot-scope="scope">
                            <span>过户手续费<span class="state_red" v-if="'write' == state">*</span></span>
                        </template>

                        <template v-slot="{row}">

                            <el-form-item label-width="0" prop="transferFee"
                                          :rules="'write' == state ? [{
                                                             required: true,
                                                             message: '请输入过户手续费',
                                                             trigger: 'blur',
                                                             validator: (rule, value, callback) => validData(rule, row.transferFee, callback)
                                                           }]:{}">
                                <el-input v-if="'write' == state" v-thousand
                                          @change="inputChange"
                                          @input="value=>{if(isNaN(row.transferFee)) { row.transferFee = '' };
                                            if(row.transferFee.indexOf('.')>0){row.transferFee=row.transferFee.slice(0,row.transferFee.indexOf('.')+3)}
                                            row.transferFee = row.transferFee.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                          v-model="row.transferFee" clearable
                                          placeholder="请输入过户手续费"></el-input>
                                <span v-thousand v-else>{{ row.transferFee|filterNull }}</span>
                            </el-form-item>
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="vehicleFee" align="center"
                        min-width="150">
                        <template slot="header" slot-scope="scope">
                            <span>过户车款<span class="state_red" v-if="'write' == state">*</span></span>
                        </template>

                        <template v-slot="{row}">

                            <el-form-item label-width="0" prop="vehicleFee"
                                          :rules="'write' == state ? [{
                                                             required: true,
                                                             message: '请输入过户车款',
                                                             trigger: 'blur',
                                                             validator: (rule, value, callback) => validData(rule, row.vehicleFee, callback)
                                                           }]:{}">
                                <el-input v-if="'write' == state" v-thousand
                                          @change="inputChange"
                                          @input="value=>{if(isNaN(row.vehicleFee)) { row.vehicleFee = '' };
                                            if(row.vehicleFee.indexOf('.')>0){row.vehicleFee=row.vehicleFee.slice(0,row.vehicleFee.indexOf('.')+3)}
                                            row.vehicleFee = row.vehicleFee.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                          v-model="row.vehicleFee" clearable
                                          placeholder="请输入过户车款"></el-input>
                                <span v-thousand v-else>{{ row.vehicleFee|filterNull }}</span>
                            </el-form-item>
                        </template>
                    </el-table-column>

                    <el-table-column
                        prop="otherFee" align="center" label="其他费用"
                        min-width="160">

                        <template v-slot="{row}">

                            <el-form-item label-width="0" prop="otherFee">
                                <el-input v-if="'write' == state" v-thousand
                                          @change="inputChange"
                                          @input="value=>{if(isNaN(row.otherFee)) { row.otherFee = '' };
                                            if(row.otherFee.indexOf('.')>0){row.otherFee=row.otherFee.slice(0,row.otherFee.indexOf('.')+3)}
                                            row.otherFee = row.otherFee.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"
                                          v-model="row.otherFee" clearable
                                          placeholder="请输入其他费用"></el-input>
                                <span v-thousand v-else>{{ row.otherFee|filterNull }}</span>
                            </el-form-item>
                        </template>
                    </el-table-column>



                    <el-table-column v-if="'write' == state" label="操作" min-width="80" align="center"
                                     class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <e-button size="mini" type="text"
                                      @click="handleDelete(scope.row, scope.$index)"
                            >删除
                            </e-button>
                        </template>
                    </el-table-column>
                </el-table>

            </div>

            <div class="card-wrap flex-column justify-end card-padding">
                <div class="card-title-wrap">
                    <span>过户发起</span>
                    <span></span>
                </div>

                <el-row :gutter="30">

                    <el-col :span="8">
                        <el-form-item label="过户前车辆上牌公司:" prop="transferBeforeId"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择过户前车辆上牌公司',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.transferBeforeId, callback)
                                       }:{}">
                            <el-select v-if="'write' == state"
                                       @change="beforeChange"
                                       filterable v-model="form.transferBeforeId" clearable disabled
                                       style="width: 100%">
                                <template v-for="(item, index) in companyList">
                                    <el-option :label="item.deptName" :value="item.deptId" :key="index"></el-option>
                                </template>
                            </el-select>
                            <span v-else>{{form.transferBeforeName|filterNull}}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="过户后车辆上牌公司:" prop="transferAfterId"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择过户后车辆上牌公司',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.transferAfterId, callback)
                                       }:{}">
                            <el-select v-if="'write' == state" filterable @change="afterChange" v-model="form.transferAfterId" clearable
                                       placeholder="请选择过户后车辆上牌公司" style="width: 100%">
                                <template v-for="(item, index) in companyList">
                                    <el-option :label="item.deptName" :value="item.deptId" :key="index"></el-option>
                                </template>
                            </el-select>
                            <span v-else>{{form.transferAfterName|filterNull}}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="过户时间:" prop="transferTime">
                            <el-date-picker v-if="'write' == state" v-model="form.transferTime" clearable style="width: 100%"
                                            type="date" placeholder="请选择过户时间" value-format="yyyy-MM-dd"></el-date-picker>
                            <span v-else>{{form.transferTime|filterNull}}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="16">
                        <el-form-item label="过户原因:" prop="transferReason">
                            <el-input v-if="'write' == state" type="textarea"
                                      v-model="form.transferReason" clearable maxlength="200"
                                      placeholder="请填写过户备注信息，不超过200个字符"></el-input>
                            <span v-else>{{ form.transferReason|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item
                            label="过户附件:"
                            prop="imageOss"
                            style="width: 100%">
                            <ImageCommon
                                isVerifyFileType
                                :fileType="['pdf', 'docx', 'xlsx', 'xls', 'jpg', 'png']"
                                :disabled="'write' != state"
                                :up-type="2"
                                info="选择附件"
                                :limit="9"
                                v-model="form.transferAnnex"
                            ></ImageCommon>
                        </el-form-item>
                    </el-col>

                </el-row>
            </div>
            <div class="card-wrap flex-column justify-end card-padding">
                <div class="card-title-wrap">
                    <span>过户费用项信息</span>
                    <span></span>
<!--                    <span>合计: <span ref="feeAmount">{{format_thousand(form.feeAmount)}}</span></span>-->
                </div>
                <el-row :gutter="30">

                    <el-col :span="8">
                        <el-form-item label="物流公司:" prop="logisticsId"
                                      :rules="'write' == state ? {
                                         required: true,
                                         message: '请选择物流公司',
                                         trigger: 'change',
                                         validator: (rule, value, callback) => validData(rule, form.logisticsId, callback)
                                       }:{}">

                            <el-select v-if="'write' == state" filterable v-model="form.logisticsId" clearable
                                       @change="logisticsChange" placeholder="请选择物流公司"
                                       style="width: 100%">
                                <template v-for="(item, index) in logisticsCompanyList">
                                    <el-option :label="item.supplierName" :value="item.supplierId" :key="index"></el-option>
                                </template>
                            </el-select>

                            <span v-else>{{form.logisticsName|filterNull}}</span>
                        </el-form-item>
                    </el-col>

<!--                    <el-col :span="8">-->
<!--                        <el-form-item label="报销类型:" prop="reimbursementType"-->
<!--                                      :rules="'write' == state ? {-->
<!--                                         required: true,-->
<!--                                         message: '请选择报销类型',-->
<!--                                         trigger: 'change',-->
<!--                                         validator: (rule, value, callback) => validData(rule, form.reimbursementType, callback)-->
<!--                                       }:{}">-->
<!--                            <el-select filterable v-if="'write' == state" v-model="form.reimbursementType" clearable-->
<!--                                       style="width: 100%">-->
<!--                                <el-option label="车管垫付-员工" :value="1" :key="1"></el-option>-->
<!--                                <el-option label="公对公-中介公司" :value="3" :key="3"></el-option>-->
<!--                            </el-select>-->
<!--                            <span v-else>{{1==form.reimbursementType?'车管垫付-员工':3==form.reimbursementType?'公对公-中介公司':'&#45;&#45;'}}</span>-->
<!--                        </el-form-item>-->
<!--                    </el-col>-->

<!--                    <el-col :span="8">-->
<!--                        <el-form-item-->
<!--                            label="运费:"-->
<!--                            prop="freightFee"-->
<!--                            :rules="'write' == state ? {-->
<!--                                         required: true,-->
<!--                                         message: '请输入运费',-->
<!--                                         trigger: 'blur',-->
<!--                                         validator: (rule, value, callback) => validData(rule, form.freightFee, callback)-->
<!--                                       }:{}">-->
<!--                            <el-input-->
<!--                                @change="inputChange"-->
<!--                                v-model="form.freightFee"-->
<!--                                clearable v-thousand-->
<!--                                v-if="'write' == state"-->
<!--                                @input="value=>{if(isNaN(form.freightFee)) { form.freightFee = '' }; if(form.freightFee.indexOf('.')>0){form.freightFee=form.freightFee.slice(0,form.freightFee.indexOf('.')+3)} form.freightFee = form.freightFee.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"-->
<!--                                placeholder="请输入运费"-->
<!--                            ></el-input>-->
<!--                            <span v-else>{{ form.freightFee | filterNull }}</span>-->
<!--                        </el-form-item>-->
<!--                    </el-col>-->

<!--                    <el-col :span="8">-->
<!--                        <el-form-item label="中介公司:" prop="intermediaryId"-->
<!--                                      :rules="'write' == state ? {-->
<!--                                         required: true,-->
<!--                                         message: '请选择中介公司',-->
<!--                                         trigger: 'change',-->
<!--                                         validator: (rule, value, callback) => validData(rule, form.intermediaryId, callback)-->
<!--                                       }:{}">-->
<!--                            <el-select filterable v-if="'write' == state" v-model="form.intermediaryId" clearable-->
<!--                                       @change="agencyChange"-->
<!--                                       style="width: 100%">-->
<!--                                <template v-for="(item, index) in agencyCompanyList">-->
<!--                                    <el-option :label="item.supplierName" :value="item.supplierId" :key="index"></el-option>-->
<!--                                </template>-->
<!--                            </el-select>-->
<!--                            <span v-else>{{form.intermediaryName|filterNull}}</span>-->
<!--                        </el-form-item>-->
<!--                    </el-col>-->

<!--                    <el-col :span="8">-->
<!--                        <el-form-item-->
<!--                            label="过户手续费:"-->
<!--                            prop="transferFee"-->
<!--                            :rules="'write' == state ? {-->
<!--                                         required: true,-->
<!--                                         message: '请输入过户手续费',-->
<!--                                         trigger: 'blur',-->
<!--                                         validator: (rule, value, callback) => validData(rule, form.transferFee, callback)-->
<!--                                       }:{}">-->
<!--                            <el-input-->
<!--                                @change="inputChange"-->
<!--                                v-model="form.transferFee"-->
<!--                                clearable v-thousand-->
<!--                                v-if="'write' == state"-->
<!--                                @input="value=>{if(isNaN(form.transferFee)) { form.transferFee = '' }; if(form.transferFee.indexOf('.')>0){form.transferFee=form.transferFee.slice(0,form.transferFee.indexOf('.')+3)} form.transferFee = form.transferFee.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"-->
<!--                                placeholder="请输入过户手续费"-->
<!--                            ></el-input>-->
<!--                            <span v-else>{{ form.transferFee | filterNull }}</span>-->
<!--                        </el-form-item>-->
<!--                    </el-col>-->


<!--                    <el-col :span="8">-->
<!--                        <el-form-item-->
<!--                            label="二手车款:"-->
<!--                            prop="secondFee">-->
<!--                            <el-input-->
<!--                                v-model="form.secondFee"-->
<!--                                clearable v-thousand-->
<!--                                v-if="'write' == state"-->
<!--                                @input="value=>{if(isNaN(form.secondFee)) { form.secondFee = '' }; if(form.secondFee.indexOf('.')>0){form.secondFee=form.secondFee.slice(0,form.secondFee.indexOf('.')+3)} form.secondFee = form.secondFee.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"-->
<!--                                placeholder="请输入二手车款"-->
<!--                            ></el-input>-->
<!--                            <span v-else>{{ form.secondFee | filterNull }}</span>-->
<!--                        </el-form-item>-->
<!--                    </el-col>-->

<!--                    <el-col :span="8">-->
<!--                        <el-form-item-->
<!--                            label="其他费用:"-->
<!--                            prop="otherFee">-->
<!--                            <el-input-->
<!--                                @change="inputChange"-->
<!--                                v-model="form.otherFee"-->
<!--                                clearable v-thousand-->
<!--                                v-if="'write' == state"-->
<!--                                @input="value=>{if(isNaN(form.otherFee)) { form.otherFee = '' }; if(form.otherFee.indexOf('.')>0){form.otherFee=form.otherFee.slice(0,form.otherFee.indexOf('.')+3)} form.otherFee = form.otherFee.replace(new RegExp(`^\\D*(\\d{8}(?:\\.\\d{0,2})?).*$`, ''), '$1')}"-->
<!--                                placeholder="请输入其他费用"-->
<!--                            ></el-input>-->
<!--                            <span v-else>{{ form.otherFee | filterNull }}</span>-->
<!--                        </el-form-item>-->
<!--                    </el-col>-->

                    <el-col :span="24">
                        <el-form-item label="备注:" prop="remark">
                            <el-input v-if="'write' == state" type="textarea"
                                      v-model="form.remark" clearable maxlength="200"
                                      placeholder="请填写过户费用项备注信息，不超过200个字符"></el-input>
                            <span v-else>{{ form.remark|filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item
                            label="费用项附件:"
                            prop="feeAnnex"
                            style="width: 100%">
                            <ImageCommon
                                isVerifyFileType
                                :fileType="['pdf', 'docx', 'xlsx', 'xls', 'jpg', 'png']"
                                :disabled="'write' != state"
                                :up-type="2"
                                info="选择附件"
                                :limit="9"
                                v-model="form.feeAnnex"
                            ></ImageCommon>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item
                            label="运费合计:"
                            prop="totalFreightFee">
                            <span >{{ form.totalFreightFee | filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item
                            label="过户手续费合计:"
                            prop="totalTransferFee">
                            <span >{{ form.totalTransferFee | filterNull }}</span>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item
                            label="其他费用合计:"
                            prop="totalOtherFee">
                            <span >{{ form.totalOtherFee | filterNull }}</span>
                        </el-form-item>
                    </el-col>

                </el-row>

            </div>

        </el-form>

    </div>
</template>

<script>

import {listDept} from "@/api/system/dept";
import {supplierList} from "@/api/memberManage/vendorList";

export default {
    dicts: ["car_business_type"],
    props: {
        value: {
            default: {},
        },
        state: {
            default: "write",
        },
    },
    computed: {
        form: {
            get() {
                return this.value;
            },
            set(value) {
                this.$emit("input", value);
            },
        },
        selectDictLabel() {
            return function (arr, val) {
                return arr
                    .map((a) => {
                        if (a.value == val) {
                            return a.label;
                        }
                    })
                    .filter((a) => a)[0];
            };
        },
    },
    watch: {
        form: {
            immediate: true,
            deep: true,
            handler(val) {
                if (this.firstEnter && val && val.carList) {
                    this.firstEnter = false



                    // this.form.transferBeforeName = this.form.carList[0].propertyRightName
                    // this.form.transferBeforeId = this.form.carList[0].propertyRightId
                    this.getCompanyOrigin()
                    this.getLogisticsCompany()
                    this.getAgencyCompany()
                }
            }
        }
    },
    data() {
        return {
            firstEnter: true,
            companyList: [],
            logisticsCompanyList: [],
            agencyCompanyList: [],
        };
    },
    methods: {
        beforeChange(val){
            let find = this.companyList.find(item=>val===item.deptId);
            if(find){
                this.form.transferBeforeName = find.deptName
            }else {
                this.form.transferBeforeName = null
            }
        },
        afterChange(val){
            let find = this.companyList.find(item=>val===item.deptId);
            if(find){
                this.form.transferAfterName = find.deptName
            }else {
                this.form.transferAfterName = null
            }
        },
        logisticsChange(val){
            let find = this.logisticsCompanyList.find(item=>val===item.supplierId);
            if(find){
                this.form.logisticsName = find.supplierName
            }else {
                this.form.logisticsName = null
            }
        },
        agencyChange(val){
            let find = this.agencyCompanyList.find(item=>val===item.supplierId);
            if(find){
                this.form.intermediaryName = find.supplierName
            }else {
                this.form.intermediaryName = null
            }
        },
        getCompanyOrigin() {
            listDept(
                {
                    deptType: '2',//组织类型（1部门 2公司）
                    regionId: null,//所在城市（省市区id）
                }).then(res => {
                this.companyList = res.data
            })
        },
        getLogisticsCompany() {
            supplierList(
                {
                    businessTypeCode:18,//物流公司
                    pageNum: 1,
                    pageSize: 100000,
                    approvalStatus: 2,
                    availableStatus: 0
                }).then(res => {
                this.logisticsCompanyList = res.rows
            })
        },
        getAgencyCompany() {
            supplierList(
                {
                    businessTypeCode:10,//中介公司
                    pageNum: 1,
                    pageSize: 100000,
                }).then(res => {
                this.agencyCompanyList = res.rows
            })
        },
        inputChange() {
            let allFreight = this.form.carList.reduce((pre, next)=>{
                return (Number(pre?pre:0) + Number(next.freightFee?next.freightFee:0)).toFixed(2)
            }, 0);

            let allTransfer = this.form.carList.reduce((pre, next)=>{
                return (Number(pre?pre:0) + Number(next.transferFee?next.transferFee:0)).toFixed(2)
            }, 0);

            let totalOtherFee = this.form.carList.reduce((pre, next)=>{
                return (Number(pre?pre:0) + Number(next.otherFee?next.otherFee:0)).toFixed(2)
            }, 0);

            this.$set(this.form, 'totalFreightFee', allFreight);
            this.$set(this.form, 'totalTransferFee', allTransfer);
            this.$set(this.form, 'totalOtherFee', totalOtherFee);
        },
        /** 删除按钮操作 */
        handleDelete(row, index) {
            this.$modal.confirm("确定删除").then(res=>{
                this.form.carList.splice(index, 1)
                this.inputChange()
            })
        },
        validData(rule, value, callback) {
            // console.log('aaa', rule, value, callback)
            if (rule.required && !value) {
                // this.$modal.msgError(`未填写${value}`);
                callback(new Error(rule.message));
            } else {
                callback();
            }
        },
        async valid() {
            return new Promise((resolve) => {
                if ('write' == this.state) {
                    this.$refs["form"].validate(valid => {
                        resolve(valid);
                    });
                } else {
                    resolve(true)
                }
            })
        },
    }
};
</script>


<style lang="scss" scoped>
::v-deep .el-form--label-top .el-form-item__label {
    padding: 0;
}

::v-deep .read-form .el-form-item__label-wrap,
::v-deep .read-form .el-form-item__content {
    margin-left: 0 !important;
}

.el-descriptions {
    margin: 0 -15px;
}

::v-deep .el-form--label-top .el-form-item__label {
    padding: 0;
}

//.el-form-item {
//    margin: 15px 0;
//    width: 100%;
//}

.el-table--small .el-table__cell {
    padding: 1px 0 !important;
}

::v-deep .el-tabs__item {
    font-size: 16px !important;
    //color: #333333;
    font-weight: bold;
}

.write-form .table_wrap .el-form-item {
    margin: 15px 0 !important;
    width: 100% !important;
}
</style>
